//
//  LYProductDetailViewController.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/15.
//

import UIKit
import MJRefresh

class LYProductDetailViewController: LYBaseViewController {
    var productId: Int?
    var orderNum: String?
    var onomit: Onomit?
    var titleName: String?
    var lepidoern: Lepidoern?
    
    private let scrollView = UIScrollView()
    private let contentView = UIView()
    private let dualRowView = DynamicDualRowView()
    private let homeTopView = LYEmohTopView()
    private var currentProductData: ProductData? = nil
    
    lazy var applyToButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle(LYlocalizedString("Apply to"), for: .normal)
        button.layer.masksToBounds = true
        button.layer.cornerRadius = 27.5
        button.addTarget(self, action: #selector(applyToAction(_ :)), for: .touchUpInside)
        button.backgroundColor = UIColor(hex: "#1E4FF3")
        button.layer.borderColor = UIColor(hex: "#FFFFFF").cgColor
        button.layer.borderWidth = 1.0
        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.title = LYlocalizedString("Product details")
        commonInitSubviews()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.scrollView.mj_header?.beginRefreshing()
    }

    func commonInitSubviews() {
        self.view.addSubview(scrollView)
        scrollView.addSubview(contentView)
        homeTopView.bgImageView.image = UIImage(named: "product_top_bg")
        homeTopView.applyButton.isHidden = true
        contentView.addSubview(homeTopView)
        contentView.addSubview(dualRowView)
        self.view.addSubview(applyToButton)
        
        scrollView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            guard let self = self else { return }
            self.fetchData()
            self.fetchAddressData()
        })
        
        if let header = scrollView.mj_header as? MJRefreshNormalHeader {
            header.setTitle("", for: .idle)
            header.setTitle("", for: .pulling)
            header.setTitle("", for: .refreshing)
            header.lastUpdatedTimeLabel?.isHidden = true
            header.stateLabel?.isHidden = true
        }
        
        scrollView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.bottom.equalToSuperview().offset(-customTabBarHeight - bottomMargin)
        }
        
        contentView.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            make.width.equalTo(scrollView)
        }
        
        homeTopView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(13)
            make.leading.trailing.equalToSuperview().inset(16)
        }
        
        dualRowView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.leading.trailing.equalToSuperview().inset(16)
            make.top.equalTo(homeTopView.snp.bottom).offset(40)
            make.bottom.equalTo(contentView)
        }
        
        applyToButton.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(16)
            make.bottom.equalToSuperview().offset(-bottomMargin)
            make.height.equalTo(55)
        }
        
        self.view.layoutIfNeeded()
        scrollView.contentSize = contentView.frame.size
    }
    
    func fetchData() {
        guard let productId = productId else {
            self.scrollView.mj_header?.endRefreshing()
            return
        }
        LYHUDUtils.showLoading()
        LYStocksManager.fetchProductDetail(productId: productId) { [weak self] product, msg, error in
            guard let self = self else { return }
            self.currentProductData = product
            if error == nil {
                if let onomit = product?.onomit {
                    self.orderNum = onomit.backable
                    let deadLine = (onomit.first ?? "0") + LYlocalizedString("days")
                    let rate = (onomit.phragmclearally?.aster?.nictian ?? "0") + "/" + LYlocalizedString("days")
                    self.homeTopView.updateDatas(maximumTitle: onomit.manyeer ?? "",
                                                 maximumAmount: onomit.aever ?? "0",
                                                 deadLine: deadLine,
                                                 rate: rate,
                                                 applyTitle: "")
                    self.onomit = onomit
                }
                
                self.lepidoern = product?.lepidoern
                
                if let turboents = product?.turboent {

                    var norlalImages = [UIImage(named: "product_normal_01"),
                                        UIImage(named: "product_normal_02"),
                                        UIImage(named: "product_normal_03"),
                                        UIImage(named: "product_normal_04")]
                    
                    var compltedImages = [UIImage(named: "product_01"),
                                          UIImage(named: "product_02"),
                                          UIImage(named: "product_03"),
                                          UIImage(named: "product_04")]
                    
                    if turboents.count == 3 {
                        norlalImages = [UIImage(named: "product_normal_01"),
                                        UIImage(named: "product_normal_02"),
                                        UIImage(named: "product_normal_uneven_03")]
                        
                        compltedImages = [UIImage(named: "product_01"),
                                          UIImage(named: "product_02"),
                                          UIImage(named: "product_uneven_03")]
                    }
                    
                    guard norlalImages.count == compltedImages.count,
                          norlalImages.count >= turboents.count else {
                        return
                    }

                    var items: [DynamicDualRowView.Item] = []
                    for (index, turboent) in turboents.enumerated() {
                        
                        let normalImage = norlalImages[index]
                        let complateImage = compltedImages[index]
                        let item = DynamicDualRowView.Item.init(turboentItem: turboent, normalImage: normalImage, complateImage: complateImage) { [weak self] in
                            guard let self = self else { return }
                            self.titleName = turboent.cipitfication
                            if let cardiarium = turboent.cardiarium,
                               cardiarium == 1 {
                                
                                guard let matrious = turboent.matrious else {
                                    return
                                }
      
                                if let scene = IdentifyScene(rawValue: matrious) {
                                    self.jumpVC(with: scene, isCompleted: true)
                                }
                            } else {
                                self.handleApplyAction()
                            }
                        }
                        items.append(item)
                    }
                    
                    // 配置视图
                    dualRowView.configure(with: items)
                }
                LYHUDUtils.hideHUD()
            } else {
                LYHUDUtils.showToast(msg)
            }
            self.scrollView.mj_header?.endRefreshing()
        }
    }
    
    func fetchAddressData() {
        LYStocksManager.fetchAddressInfo(productId: self.productId ?? -1) { [weak self] address, msg, error in
            guard let _ = self else { return }
            if error == nil,
               let address = address {
                LYUserDefaults.shared.setObject(address, forKey: addressKey)
            }
        }
    }
    
    @objc func applyToAction(_ sender: UIButton) {
        handleApplyAction()
    }
    
    func handleApplyAction() {
        guard let currentProductData = self.currentProductData else {
            return
        }
        
        guard let stly = currentProductData.stly else {
            NotificationCenter.default.post(name: .orderListFollowKey,
                                            object: nil,
                                            userInfo: ["customData": self.onomit as Any,
                                                       "orderNum": self.orderNum ?? ""])
            return
        }
        
        guard let matrious = stly.matrious else {
            return
        }
        
        self.titleName = stly.cipitfication
        
        if let scene = IdentifyScene(rawValue: matrious) {
            self.jumpVC(with: scene, isCompleted: false)
        }
    }
    
    func jumpVC(with scene: IdentifyScene, isCompleted: Bool) {
        switch scene {
        case .public:
            if isCompleted {
                self.goToPublicCompletedVC()
            } else {
                goToPublicVC()
            }
        case .personal:
            goToPersonalVC()
        case .ext:
            goToExtVC()
        case .bank:
            goToBankVC()
        }
    }
    
    func goToPublicVC() {
        let publicVC = LYPublicViewController()
        publicVC.productId = productId
        publicVC.orderNum = orderNum
        publicVC.onomit = self.onomit
        publicVC.titleName = titleName
        self.navigationController?.pushViewController(publicVC, animated: true)
    }
    
    func goToPublicCompletedVC() {
        let publicVC = LYPublicCompletedViewController()
        publicVC.productId = productId
        publicVC.orderNum = orderNum
        publicVC.onomit = self.onomit
        self.navigationController?.pushViewController(publicVC, animated: true)
    }
    
    func goToPersonalVC() {
        let personalVC = LYPersonalViewController()
        personalVC.productId = productId
        personalVC.orderNum = orderNum
        personalVC.onomit = self.onomit
        personalVC.titleName = titleName
        self.navigationController?.pushViewController(personalVC, animated: true)
    }
    
    func goToExtVC() {
        let extVC = LYExtViewController()
        extVC.productId = productId
        extVC.orderNum = orderNum
        extVC.onomit = self.onomit
        extVC.titleName = titleName
        self.navigationController?.pushViewController(extVC, animated: true)
    }
    
    func goToBankVC() {
        let bankVC = LYBankViewController()
        bankVC.productId = productId
        bankVC.orderNum = orderNum
        bankVC.onomit = self.onomit
        bankVC.titleName = titleName
        self.navigationController?.pushViewController(bankVC, animated: true)
    }
}

enum IdentifyScene: String, RawRepresentable {
    case `public` = "hygrwhy"
    case personal = "grammably"
    case ext = "stirp"
    case bank = "nuchfication"
}

